package main

import (
	"database/sql"
	"fmt"
	"time"

	_ "github.com/mattn/go-sqlite3"
)

func printtf(format string, a ...any) {
	print(time.Now().In(time.FixedZone("CST", 28800)).Format("\r[01-02 15:04:05] ") + fmt.Sprintf(format, a...))
}
func printt(a ...any) {
	a = append([]any{time.Now().In(time.FixedZone("CST", 28800)).Format("[01-02 15:04:05]")}, a...)
	fmt.Println(a...)
}

var db *sql.DB

type orderInfo struct {
	OrderID    int64
	UserID     int64
	CreateTime int64
	PayTime    int64
	Price      int64
	PayMethod  int64
}

func init() {
	go func() {
		var err error
		db, err = sql.Open("sqlite3", "./orders.db")
		if err != nil {
			printt(err)
			return
		}

		// 创建订单表
		createTable()

		// 新建一个订单
		//orderID, realPrice := addOrder(2, 123)
		//printt("订单ID", orderID, "需支付", realPrice)

		//支付
		//orderID = payPrice(realPrice, 1)
		//printt("已支付 订单ID", orderID)

		// 修改订单的支付日期和支付方式
		//updateOrder(orderID, time.Now().Unix()+9999999, 2)
		// 删除一个订单
		//delOrder(orderID)
		// 查询订单信息
		//queryAllOrders()
		//order := checkOrder(666)
		// if order.CreateTime == -1 {
		// 	printt("订单未创建")
		// } else if order.PayTime == -1 {
		// 	printt("订单未支付")
		// }
		// printt("订单", order)
		for {
			delUnpaidOrders()
			time.Sleep(12 * time.Hour)
		}
	}()
}

//新建数据表
func createTable() {
	_, err := db.Exec(`CREATE TABLE IF NOT EXISTS Orders (
		order_id INTEGER PRIMARY KEY AUTOINCREMENT,
		user_id INTEGER NOT NULL,
		create_time INTEGER NOT NULL,
		pay_time INTEGER NOT NULL,
		price INTEGER NOT NULL,
		pay_method INTEGER NOT NULL
	);`) //pay_method 0未支付 1微信 2支付宝
	if err != nil {
		printt(err)
		return
	}
}

//新建订单,返回订单ID和需支付金额,order==-1 出错,realPrice==0 当前订单太多
func addOrder(userID int64, price int64) (orderID, realPrice int64) {
	unpaidOrders := queryUnpaidOrders()
	unpaidPrices := map[int64]bool{}
	for _, order := range unpaidOrders {
		unpaidPrices[order.Price] = true
	}
	f := false
	for realPrice = price; realPrice < price+100; realPrice++ {
		if _, ok := unpaidPrices[realPrice]; !ok {
			f = true
			break
		}
	}
	if !f {
		return -1, 0
	}
	price = realPrice
	result, err := db.Exec("INSERT INTO Orders (user_id, create_time, pay_time, price, pay_method) VALUES (?, ?, ?, ?, ?)", userID, time.Now().Unix(), -1, price, 0)
	if err != nil {
		printt(err)
		return -1, realPrice
	}
	// 获取刚刚插入行的自增ID
	orderID, err = result.LastInsertId()
	if err != nil {
		printt(err)
		return -1, realPrice
	}
	printtf("创建订单ID: %v, 价格: %v \n", orderID, realPrice)
	return
}

//更新订单ID的付款时间的方式
func updateOrder(orderID int64, payTime int64, payMethod int64) {
	_, err := db.Exec("UPDATE Orders SET pay_time = ?, pay_method = ? WHERE order_id = ?", payTime, payMethod, orderID)
	if err != nil {
		printt(err)
		return
	}
}

//收到付款金额返回订单ID,不存在返回-1
func payPrice(price, payMethod int64) (orderID int64) {
	if tomlInfo.Post != "" {
		Post(price, payMethod)
		return -1
	}
	unpaidOrders := queryUnpaidOrders()
	now := time.Now().Unix()
	for _, order := range unpaidOrders {
		if price == order.Price {
			updateOrder(order.OrderID, now, payMethod)
			printtf("订单ID: %v, 价格: %v 已付款 方式:%v\n", order.OrderID, price, payMethod)
			return order.OrderID
		}
	}
	printtf("其他来源的收款:%v %v\n", price, payMethod)
	db.Exec("INSERT INTO Orders (user_id, create_time, pay_time, price, pay_method) VALUES (?, ?, ?, ?, ?)", -1, now, now, price, payMethod)
	return -1
}

//删除订单ID的信息
func delOrder(orderID int64) {
	_, err := db.Exec("DELETE FROM Orders WHERE order_id = ?", orderID)
	if err != nil {
		printt(err)
		return
	}
}

//获取所有订单信息
func queryAllOrders() {
	rows, err := db.Query("SELECT * FROM Orders")
	if err != nil {
		printt(err)
		return
	}
	defer rows.Close()

	for rows.Next() {
		var orderID int64
		var userID int64
		var createTime int64
		var payTime interface{}
		var price int64
		var payMethod int64
		err := rows.Scan(&orderID, &userID, &createTime, &payTime, &price, &payMethod)
		if err != nil {
			printt(err)
			return
		}
		printtf("订单ID: %v, 用户ID: %v, 创建时间: %v, 支付时间: %v, 价格: %v, 支付方式: %v\n", orderID, userID, createTime, payTime, price, payMethod)
	}
}

//获取订单ID的订单信息
func checkOrder(orderID int64) (order orderInfo) {
	var userID, createTime, payTime, price, payMethod int64
	userID, createTime, payTime, price, payMethod = -1, -1, -1, 0, 0
	order = orderInfo{}
	row := db.QueryRow("SELECT user_id, create_time, pay_time, price, pay_method FROM Orders WHERE order_id = ?", orderID)
	err := row.Scan(&userID, &createTime, &payTime, &price, &payMethod)
	if err != nil {
		return orderInfo{orderID, userID, createTime, payTime, price, payMethod}
	}
	return orderInfo{orderID, userID, createTime, payTime, price, payMethod}
}

//获取330秒内未支付订单
func queryUnpaidOrders() (orders []orderInfo) {
	orders = []orderInfo{}
	now := time.Now().Unix()
	cutOffTime := now - 330 // 330秒前的时间戳

	rows, err := db.Query("SELECT order_id, user_id, create_time, price FROM Orders WHERE pay_time == -1 AND create_time > ?", cutOffTime)
	if err != nil {
		printt(err)
		return
	}
	defer rows.Close()

	//printtf("查询到未支付且创建时间不超过330秒的订单：\n")
	for rows.Next() {
		var orderID int64
		var userID int64
		var createTime int64
		var price int64
		err := rows.Scan(&orderID, &userID, &createTime, &price)
		if err != nil {
			printt(err)
			return
		}
		orders = append(orders, orderInfo{orderID, userID, createTime, -1, price, 0})
		//printtf("订单ID: %v, 价格: %v\n", orderID, price)
	}
	return
}

//删除12小时前的未支付订单
func delUnpaidOrders() {
	delOrderIDs := []int64{}
	now := time.Now().Unix()
	cutOffTime := now - 43200 // 43200秒前的时间戳

	rows, err := db.Query("SELECT order_id FROM Orders WHERE pay_time == -1 AND create_time < ?", cutOffTime)
	if err != nil {
		printt(err)
		return
	}
	defer rows.Close()

	//printtf("查询到未支付且创建时间超过秒的订单：\n")
	for rows.Next() {
		var orderID int64
		err := rows.Scan(&orderID)
		if err != nil {
			printt(err)
			continue
		}
		delOrderIDs = append(delOrderIDs, orderID)
	}
	for _, orderId := range delOrderIDs {
		delOrder(orderId)
	}
	return
}
